<template>
  <div class="user-manage">
    <!-- 用户列表 -->
    <wrapper-main v-if="pageType === 'list'" v-loading="loading">
      <span slot="main-header">用户管理</span>
      <checkbox-table
        :tableHeaderData="tableHeaderData"
        :tableData="tableData"
        @setStyle="setTableColStyle"
        @deleteBtnClick="deleteBtnClick"
        @editBtnClick="editBtnClick"
        @selectionChange="selectionChange"
        :isDelete="role === '0'"
      >
      </checkbox-table>

      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="current"
        layout="total, prev, pager, next"
        :total="total"
        :page-size="10"
      >
      </el-pagination>
    </wrapper-main>
    <!-- 用户编辑 -->
    <wrapper-main v-if="pageType === 'edit'" v-loading="loading">
      <span slot="main-header">修改用户信息</span>
      <el-form
        :model="userForm"
        :rules="userFormRules"
        ref="userForm"
        label-width="100px"
        style="width: 500px; margin-top: 20px"
      >
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户类别" prop="u_type">
          <el-select v-model="userForm.u_type" :disabled="role === '1'">
            <el-option
              v-for="item in userSelectList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="userForm.sex" :disabled="role === '1'">
            <el-option label="男" :value="0"></el-option>
            <el-option label="女" :value="1"></el-option>
            <el-option label="无性" :value="2"></el-option>
            <el-option label="双性" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="userForm.password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <template slot="main-footer">
        <span class="footer-btn">
          <el-button @click="back2UserList">取消</el-button>
          <el-button type="primary" @click="updateUserList('userForm')"
            >保存</el-button
          >
        </span>
      </template>
    </wrapper-main>
  </div>
</template>
<script>
export default {
  name: "user-manage",
  props: {},
  data() {
    const validatePhone = (rule, value, callback) => {
      let reg = /^1[345789]\d{9}$/;
      if (value === "" || reg.test(value)) callback();
      else callback(new Error("请输入正确的手机号码"));
    };
    return {
      userSelectList: [
        {
          name: "管理员",
          value: "0",
        },
        {
          name: "普通用户",
          value: "1",
        },
      ],
      pageType: "list",
      loading: true,
      tableHeaderData: [
        {
          name: "索引",
          property: "id",
        },
        {
          name: "名称",
          property: "name",
        },
        {
          name: "密码",
          property: "password",
        },
        {
          name: "邮箱",
          property: "email",
        },
        {
          name: "性别",
          property: "sex",
        },
        {
          name: "账号类型",
          property: "u_type",
        },
        {
          name: "头像名",
          property: "avatar",
        },
        {
          name: "注册时间",
          property: "create_time",
        },
        {
          name: "更新时间",
          property: "update_time",
        },
      ],
      tableData: [],
      selectArray: [],
      userForm: {
        email: "",
        u_type: "",
        name: "",
        password: "",
        sex: "",
        u_type: "",
        user_id: "",
      },
      userFormRules: {
        email: [
          { required: true, trigger: "blur", message: "请输入邮箱地址" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        u_type: [
          { required: true, trigger: "blur", message: "请输入用户类别" },
        ],
        phone: [{ validator: validatePhone, trigger: "blur" }],
      },
      editRowId: "",
      listQuery: {
        page: 1,
        limit: 10,
      },
      userInfo: "",
      total: 1000,
      current: 1,
    };
  },
  computed: {
    role() {
      if (this.$store.state.user) return this.$store.state.user.role;
      else return "";
    },
    userId() {
      if (this.$store.state.user) return this.$store.state.user.id;
      else return "";
    },
  },
  mounted() {
    this.userInfo = JSON.parse(window.sessionStorage.getItem("userInfo"));
    this.getPlList();
  },
  methods: {
    // 点击页码
    async handleCurrentChange() {
      this.listQuery.page = this.current;
      this.getPlList();
    },
    getPlList() {
      this.loading = true;
      this.$axios
        .get("/admin/user_list/", {
          params: {
            u_type: this.userInfo.u_type,
            page: this.listQuery.page,
            limit: this.listQuery.limit,
          },
        })
        .then((ret) => {
          this.tableData = ret.data.data;
          this.listQuery = ret.data.listQuery;
          this.total = ret.total;
          this.loading = false;
        })
        .catch((res) => {
          this.$message.error(res.response.data.message);
          this.loading = false;
        });
    },

    setTableColStyle(params) {
      if (params.column.label === "电话") params.column.minWidth = 100;
      else if (params.column.label === "地址") params.column.minWidth = 120;
    },
    deleteBtnClick(status) {
      if (status === "part" && this.selectArray.length === 0) return;

      this.$confirm("此操作将永久删除且不可撤销，是否继续", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const param = {};

        if (status === "part") {
          param.id = this.selectArray.join(",");
          if (param.id === "") {
            this.load = false;
            return false;
          }
        } else if (status === "all") {
          param.id = status;
        } else {
          param.id = status.id;
        }

        this.deleteUser(param);
      });
    },
    editBtnClick(row) {
      console.log(row);
      this.pageType = "edit";
      this.editRowId = row.id;
      this.userForm.email = row.email;
      this.userForm.user_id = row.id;
      this.userForm.name = row.name;
      this.userForm.password = row.password;
      this.userForm.sex = row.sex;
      this.userForm.u_type = row.u_type;
    },
    selectionChange(selection) {
      const arr = [];
      selection.forEach((d) => {
        arr.push(d.id);
      });
      this.selectArray = arr;
    },
    deleteUser(param) {
      this.$http("get", "deleteUser", param)
        .then((data) => {
          this.load = false;
          if (data === "success") {
            this.notify({ type: "success", message: "删除成功" });
            this.getUserList();
          } else {
            this.$message.error(data || "删除失败");
          }
        })
        .catch((error) => {
          this.load = false;
          this.$message.error(error);
        });
    },
    getUserList(page = 1) {
      const param = {
        role: this.role,
        user_id: this.userId,
      };
      this.load = true;

      this.$http("get", "userList", param)
        .then((res) => {
          this.load = false;
          this.tableData = res.data;
        })
        .catch((error) => {
          this.load = false;
          this.$message.error(error);
        });
    },
    back2UserList() {
      this.pageType = "list";
      this.$refs.userForm.resetFields();
    },
    updateUserList(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.load = true;
          this.$axios
            .post(`/admin/update/`, this.userForm)
            .then((ret) => {
              this.$message.success("更新成功");
            })
            .catch((res) => {
              this.$message.error(res.response.data.message);
            });
        }
      });
    },
    notify({
      title = "",
      message = "成功",
      type = "",
      showClose = false,
    } = {}) {
      this.$notify({
        title: title,
        message: message,
        type: type,
        showClose: showClose,
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.user-manage {
  width: 100%;
  height: 100%;
  background: #fff;
}
</style>
